import React, { useState, useEffect, useRef } from 'react';
import { MCPClient } from '../mcpClient.js';
import { AIProvider } from '../aiProvider.js';
import { ConversationManager } from '../conversationManager.js';
import Message from './Message.js';
import ToolCall from './ToolCall.js';

function App() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);
  const [status, setStatus] = useState('正在初始化...');
  const [aiModel, setAiModel] = useState('');
  const chatContainerRef = useRef(null);

  // 初始化客户端、AI 提供者和对话管理器
  const mcpClientRef = useRef(null);
  const aiProviderRef = useRef(null);
  const conversationManagerRef = useRef(null);

  // 初始化应用
  useEffect(() => {
    async function initialize() {
      try {
        // 加载配置
        const response = await fetch('/config.json');
        const config = await response.json();

        // 初始化组件
        mcpClientRef.current = new MCPClient(config.mcp_servers, config.client_settings);
        aiProviderRef.current = new AIProvider(config.ai_models);
        conversationManagerRef.current = new ConversationManager();
        
        // 连接 MCP 服务器
        setStatus('正在连接 MCP 服务器...');
        await mcpClientRef.current.connectAll();
        
        // 获取所有工具
        const tools = await mcpClientRef.current.getAllTools();
        aiProviderRef.current.setTools(tools);
        
        // 设置当前 AI 模型
        setAiModel(config.ai_models.default);
        
        // 添加欢迎消息
        setMessages([{
          id: Date.now(),
          type: 'system',
          content: '✅ 系统初始化成功! 请开始你的对话...'
        }]);
        
        setStatus('准备就绪');
      } catch (error) {
        console.error('初始化失败:', error);
        setStatus(`初始化失败: ${error.message}`);
        setMessages([{
          id: Date.now(),
          type: 'system',
          content: `❌ 初始化失败: ${error.message}`
        }]);
      }
    }
    
    initialize();
    
    // 清理函数
    return () => {
      if (mcpClientRef.current) {
        mcpClientRef.current.disconnectAll();
      }
    };
  }, []);
  
  // 消息更新后自动滚动到底部
  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  }, [messages]);
  
  // 处理发送消息
  const handleSendMessage = async () => {
    if (!input.trim() || isProcessing) return;
    
    const userInput = input.trim();
    setInput('');
    setIsProcessing(true);
    
    // 添加用户消息到界面
    const newUserMessage = {
      id: Date.now(),
      type: 'user',
      content: userInput
    };
    
    setMessages(prev => [...prev, newUserMessage]);
    
    // 处理命令
    if (userInput.startsWith('/')) {
      await handleCommand(userInput);
      setIsProcessing(false);
      return;
    }
    
    try {
      // 添加用户消息到对话历史
      conversationManagerRef.current.addMessage('user', userInput);
      
      // 显示 AI 正在思考
      const thinkingMsgId = Date.now();
      setMessages(prev => [...prev, {
        id: thinkingMsgId,
        type: 'ai-thinking',
        content: '思考中...'
      }]);
      
      // 获取对话历史
      const messages = conversationManagerRef.current.getMessages();
      
      // 调用 AI 模型
      const response = await aiProviderRef.current.chat(messages);
      
      // 移除思考消息
      setMessages(prev => prev.filter(msg => msg.id !== thinkingMsgId));
      
      // 处理工具调用
      if (response.tool_calls && response.tool_calls.length > 0) {
        // 显示工具调用信息
        for (const toolCall of response.tool_calls) {
          const toolCallMsg = {
            id: Date.now() + Math.random(),
            type: 'tool-call',
            toolName: toolCall.function.name,
            arguments: toolCall.function.arguments
          };
          
          setMessages(prev => [...prev, toolCallMsg]);
          
          // 执行工具调用
          const result = await mcpClientRef.current.callTool(
            toolCall.function.name,
            JSON.parse(toolCall.function.arguments)
          );
          
          // 显示工具调用结果
          const toolResultMsg = {
            id: Date.now() + Math.random(),
            type: 'tool-result',
            toolName: toolCall.function.name,
            result: JSON.stringify(result, null, 2)
          };
          
          setMessages(prev => [...prev, toolResultMsg]);
          
          // 添加工具结果到对话历史
          conversationManagerRef.current.addMessage('tool', JSON.stringify(result), {
            tool_call_id: toolCall.id
          });
        }
        
        // 获取最终回复
        const finalMessages = conversationManagerRef.current.getMessages();
        const finalResponse = await aiProviderRef.current.chat(finalMessages);
        
        // 显示 AI 最终回复
        const aiMessage = {
          id: Date.now(),
          type: 'ai',
          content: finalResponse.content
        };
        
        setMessages(prev => [...prev, aiMessage]);
        
        // 保存 AI 回复到对话历史
        conversationManagerRef.current.addMessage('assistant', finalResponse.content);
      } else {
        // 显示 AI 回复
        const aiMessage = {
          id: Date.now(),
          type: 'ai',
          content: response.content
        };
        
        setMessages(prev => [...prev, aiMessage]);
        
        // 保存 AI 回复到对话历史
        conversationManagerRef.current.addMessage('assistant', response.content);
      }
    } catch (error) {
      console.error('处理消息失败:', error);
      
      // 显示错误消息
      setMessages(prev => [...prev, {
        id: Date.now(),
        type: 'system',
        content: `❌ 错误: ${error.message}`
      }]);
    }
    
    setIsProcessing(false);
  };
  
  // 处理命令
  const handleCommand = async (command) => {
    const [cmd, ...args] = command.slice(1).split(' ');
    
    switch (cmd) {
      case 'help':
        showHelp();
        break;
      case 'tools':
        await showTools();
        break;
      case 'servers':
        await showServers();
        break;
      case 'clear':
        clearChat();
        break;
      case 'model':
        if (args[0]) {
          switchModel(args[0]);
        } else {
          showCurrentModel();
        }
        break;
      default:
        setMessages(prev => [...prev, {
          id: Date.now(),
          type: 'system',
          content: `❌ 未知命令: ${cmd}`
        }]);
    }
  };
  
  // 显示帮助信息
  const showHelp = () => {
    setMessages(prev => [...prev, {
      id: Date.now(),
      type: 'system',
      content: `
📖 MCP Client 帮助
==================
/help     - 显示此帮助
/tools    - 显示所有可用工具
/servers  - 显示服务器状态
/clear    - 清空对话历史
/model    - 显示当前模型
/model <n> - 切换模型

💡 直接输入消息开始与 AI 对话
      `
    }]);
  };
  
  // 显示所有工具
  const showTools = async () => {
    try {
      const tools = await mcpClientRef.current.getAllTools();
      
      setMessages(prev => [...prev, {
        id: Date.now(),
        type: 'system',
        content: `
🛠️ 可用工具:
${tools.map(tool => `• ${tool.function.name} - ${tool.function.description}`).join('\n')}
        `
      }]);
    } catch (error) {
      setMessages(prev => [...prev, {
        id: Date.now(),
        type: 'system',
        content: `❌ 获取工具失败: ${error.message}`
      }]);
    }
  };
  
  // 显示服务器状态
  const showServers = async () => {
    const servers = mcpClientRef.current.getServerStatus();
    
    setMessages(prev => [...prev, {
      id: Date.now(),
      type: 'system',
      content: `
🖥️ 服务器状态:
${servers.map(server => {
  const status = server.connected ? '✅ 已连接' : '❌ 未连接';
  return `• ${server.name} ${status} - ${server.description}`;
}).join('\n')}
      `
    }]);
  };
  
  // 清空聊天历史
  const clearChat = () => {
    conversationManagerRef.current.clear();
    setMessages([{
      id: Date.now(),
      type: 'system',
      content: '✅ 对话历史已清空'
    }]);
  };
  
  // 切换模型
  const switchModel = (modelName) => {
    if (aiProviderRef.current.switchModel(modelName)) {
      setAiModel(modelName);
      setMessages(prev => [...prev, {
        id: Date.now(),
        type: 'system',
        content: `✅ 已切换到模型: ${modelName}`
      }]);
    } else {
      setMessages(prev => [...prev, {
        id: Date.now(),
        type: 'system',
        content: `❌ 未知模型: ${modelName}`
      }]);
    }
  };
  
  // 显示当前模型
  const showCurrentModel = () => {
    setMessages(prev => [...prev, {
      id: Date.now(),
      type: 'system',
      content: `🤖 当前模型: ${aiModel}`
    }]);
  };
  
  // 按下回车键发送消息
  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };
  
  // 渲染消息
  const renderMessages = () => {
    return messages.map((message) => {
      if (message.type === 'tool-call') {
        return (
          <ToolCall 
            key={message.id}
            name={message.toolName}
            args={message.arguments}
            isResult={false}
          />
        );
      }
      
      if (message.type === 'tool-result') {
        return (
          <ToolCall 
            key={message.id}
            name={message.toolName}
            result={message.result}
            isResult={true}
          />
        );
      }
      
      return (
        <Message 
          key={message.id}
          type={message.type}
          content={message.content}
        />
      );
    });
  };
  
  // 渲染命令按钮
  const renderCommandButtons = () => {
    const commands = [
      { label: '帮助', command: '/help' },
      { label: '工具', command: '/tools' },
      { label: '服务器', command: '/servers' },
      { label: '清空', command: '/clear' }
    ];
    
    return (
      <div className="command-buttons">
        {commands.map((cmd, index) => (
          <button 
            key={index} 
            className="command-button"
            onClick={() => {
              setInput(cmd.command);
              handleSendMessage();
            }}
          >
            {cmd.label}
          </button>
        ))}
      </div>
    );
  };
  
  return (
    <div className="container">
      <div className="header">
        <h1>MCP 客户端</h1>
        <div>{status}</div>
      </div>
      
      <div className="chat-container" ref={chatContainerRef}>
        {renderMessages()}
      </div>
      
      {renderCommandButtons()}
      
      <div className="input-container">
        <textarea
          className="input-field"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyPress={handleKeyPress}
          placeholder="输入消息或命令..."
          disabled={isProcessing}
          rows={2}
        />
        <button
          className="send-button"
          onClick={handleSendMessage}
          disabled={!input.trim() || isProcessing}
        >
          {isProcessing ? (
            <div className="loading-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          ) : '发送'}
        </button>
      </div>
    </div>
  );
}

export default App; 